package com.eps.security;

import org.apache.log4j.Logger;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

public class AccessDecisionManagerImpl implements AccessDecisionManager {

    private static final Logger logger = Logger.getLogger(AccessDecisionManager.class);

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        if (logger.isInfoEnabled()) {
            logger.debug("decide(Authentication, Object," +
                    "Collection<ConfigAttribute>)~start");
        }
        if (configAttributes == null) {
            if (logger.isInfoEnabled()) {
                logger.info("decide(Authentication, Object," +
                        "Collection<ConfigAttribute>)~end");
            }
            return;
        }
        if (logger.isInfoEnabled()) {
            logger.info("????????url??: " + object.toString());
        }

        for (ConfigAttribute ca : configAttributes) {
            String needRole = ca.getAttribute();

            for (GrantedAuthority ga : authentication.getAuthorities()) {
                if (needRole.equals(ga.getAuthority())) {
                    if (logger.isInfoEnabled()) {
                        logger.info("??????" + needRole + " ?? " +
                                "???" + ga.getAuthority() + " ?????.");
                        logger.info("decide(Authentication, Object," +
                                "Collection<ConfigAttribute>)~end");
                    }
                    return;
                }
            }
        }
        throw new AccessDeniedException("??????");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
